package fr.cephb.operon.server.ws;

import java.io.PrintStream;


import javax.xml.ws.Endpoint;
import fr.cephb.joperon.core.bio.Assembly;
import fr.cephb.operon.common.CmdLineApplication;


public class SNPToolPublisher extends CmdLineApplication
	{
	private static final String DEFAULT_HOST="http://localhost:8070";
	private static final String DEFAULT_CONTEXT="/snptool";
	private static final int DEFAULT_LIMIT=10000;
	private Assembly assembly= Assembly.getDefaultAssembly();

	
	private SNPToolPublisher()
		{
		
		
		}

	
	public Assembly getAssembly() {
		return assembly;
	}
	
	@Override
	protected void usage(PrintStream out) {
		out.println("Author: Pierre Lindenbaum PhD.");
		out.println("A publisher for the SNP tool web services.");
		super.usage(out);
		out.println(" --context <web-context> default:"+DEFAULT_CONTEXT);
		out.println(" --host <host> default:"+DEFAULT_HOST);
		out.println(" --limit <int> default:"+DEFAULT_LIMIT);
		out.println(" -a <assemby-id> default:"+Assembly.getDefaultAssembly().getId());
		for(Assembly as: Assembly.getAssemblies())
			{
			out.println("   "+as.getId()+" : "+as.getName());
			}
		}
	

	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SNPToolPublisher app= new SNPToolPublisher();
			int optind=0;
			int index=0;
			int limit = DEFAULT_LIMIT;
			String host=DEFAULT_HOST;
			String context=DEFAULT_CONTEXT;
			//loop over arguments
		    while(optind<args.length)
				{
				if((index=app.parseOption(args,optind))!=-1)
				 	{
					optind= index; 
				 	}
				else if(args[optind].equals("-a"))
				 	{
					app.assembly=Assembly.getAssemblyById(Integer.parseInt(args[++optind]));
				 	}
				else if(args[optind].equals("--host"))
				 	{
					host=args[++optind];
				 	}
				else if(args[optind].equals("--context"))
				 	{
					context=args[++optind];
				 	}
				else if(args[optind].equals("--limit"))
				 	{
					limit=Integer.parseInt(args[++optind]);
				 	}
				 else if (args[optind].equals("--"))
				     {
				     ++optind;
				     break;
				     }
				else if (args[optind].startsWith("-"))
				     {
				     System.err.println("bad argument " + args[optind]);
				     System.exit(-1);
				     }
				else
				     {
				     break;
				     }
				++optind;
				}
	
		   
		    
		    
		    //check assembly
		    if(app.assembly==null)
		    	{
		    	app.assembly= Assembly.getDefaultAssembly();
		    	app.log().info("Set assembly to "+app.assembly);
		    	}
		    
		    SnpToolImpl implementator=new SnpToolImpl();
		    implementator.setAssembly(app.getAssembly());
		    implementator.setLimitSnpCount(limit);
		    Endpoint endpoint = Endpoint.create(implementator);
		    endpoint.publish(host+context);
            System.out.println("Starting WebService context "+host+context);
            System.out.println("Press Ctrl-C to end");
			}
		catch (Exception e)
			{
			e.printStackTrace();
			}

	}
	}
